#!/bin/bash
# -*- coding: utf-8 -*-
# 新闻日报系统状态检查脚本

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 打印横幅
print_banner() {
    echo "============================================================"
    echo "📰 MorningByte 新闻日报系统 - 状态检查"
    echo "============================================================"
    echo "检查时间: $(date '+%Y-%m-%d %H:%M:%S')"
    echo "============================================================"
}

# 检查Python环境
check_python() {
    print_info "检查Python环境..."
    
    if command -v python3 &> /dev/null; then
        PYTHON_CMD="python3"
    elif command -v python &> /dev/null; then
        PYTHON_CMD="python"
    else
        print_error "未找到Python环境"
        return 1
    fi
    
    PYTHON_VERSION=$($PYTHON_CMD --version 2>&1 | cut -d' ' -f2)
    print_success "Python版本: $PYTHON_VERSION"
    return 0
}

# 检查依赖包
check_dependencies() {
    print_info "检查依赖包..."
    
    local missing_packages=()
    local total_packages=0
    
    # 检查每个依赖包
    packages=("openai" "requests" "feedparser" "bs4" "lxml" "schedule")
    
    for package in "${packages[@]}"; do
        total_packages=$((total_packages + 1))
        if $PYTHON_CMD -c "import $package" 2>/dev/null; then
            print_success "✓ $package"
        else
            print_error "✗ $package"
            missing_packages+=("$package")
        fi
    done
    
    if [ ${#missing_packages[@]} -eq 0 ]; then
        print_success "所有依赖包已安装 ($total_packages/$total_packages)"
        return 0
    else
        print_error "缺少依赖包: ${missing_packages[*]}"
        return 1
    fi
}

# 检查配置文件
check_config() {
    print_info "检查配置文件..."
    
    if [ ! -f "email_config.py" ]; then
        print_error "配置文件不存在: email_config.py"
        return 1
    fi
    
    if $PYTHON_CMD -c "from email_config import validate_config; errors = validate_config(); exit(0 if not errors else 1)" 2>/dev/null; then
        print_success "配置文件验证通过"
        
        # 显示配置信息
        print_info "当前配置:"
        $PYTHON_CMD -c "
from email_config import get_config_info
info = get_config_info()
print(f'  发送邮箱: {info[\"sender_email\"]}')
print(f'  接收邮箱: {info[\"recipient_email\"]}')
print(f'  发送时间: 每天 {info[\"send_time\"]}')
print(f'  RSS源: {info[\"rss_url\"]}')
print(f'  最大新闻数: {info[\"max_news_items\"]}')
"
        return 0
    else
        print_error "配置文件验证失败"
        return 1
    fi
}

# 检查进程状态
check_processes() {
    print_info "检查进程状态..."
    
    PIDS=$(pgrep -f "start_daily_news.py\|scheduler.py\|news_daily.py" 2>/dev/null || true)
    
    if [ -n "$PIDS" ]; then
        print_success "服务正在运行 (PID: $PIDS)"
        
        # 显示进程详情
        for pid in $PIDS; do
            if ps -p $pid > /dev/null 2>&1; then
                print_info "  进程 $pid: $(ps -p $pid -o comm= 2>/dev/null || echo 'unknown')"
            fi
        done
        return 0
    else
        print_warning "服务未运行"
        return 1
    fi
}

# 检查系统服务
check_system_service() {
    print_info "检查系统服务..."
    
    if command -v systemctl &> /dev/null; then
        if systemctl list-unit-files | grep -q morningbyte-news.service; then
            if systemctl is-active --quiet morningbyte-news.service 2>/dev/null; then
                print_success "系统服务正在运行"
                return 0
            else
                print_warning "系统服务已安装但未运行"
                return 1
            fi
        else
            print_info "系统服务未安装"
            return 1
        fi
    else
        print_info "未找到systemctl，跳过系统服务检查"
        return 1
    fi
}

# 检查日志文件
check_logs() {
    print_info "检查日志文件..."
    
    if [ -d "logs" ]; then
        LOG_COUNT=$(find logs -name "*.log" 2>/dev/null | wc -l)
        if [ $LOG_COUNT -gt 0 ]; then
            print_success "找到 $LOG_COUNT 个日志文件"
            
            # 显示最新的日志文件
            LATEST_LOG=$(find logs -name "*.log" -type f -printf '%T@ %p\n' 2>/dev/null | sort -n | tail -1 | cut -d' ' -f2-)
            if [ -n "$LATEST_LOG" ]; then
                print_info "最新日志: $LATEST_LOG"
                print_info "最后几行日志:"
                tail -5 "$LATEST_LOG" 2>/dev/null | sed 's/^/  /'
            fi
        else
            print_warning "未找到日志文件"
        fi
    else
        print_warning "日志目录不存在"
    fi
}

# 检查网络连接
check_network() {
    print_info "检查网络连接..."
    
    # 检查RSS源连接
    if curl -s --connect-timeout 5 "https://rss.aishort.top/?type=36kr" > /dev/null 2>&1; then
        print_success "RSS源连接正常"
    else
        print_error "RSS源连接失败"
    fi
    
    # 检查大模型API连接
    if curl -s --connect-timeout 5 "https://maas-api.lanyun.net" > /dev/null 2>&1; then
        print_success "大模型API连接正常"
    else
        print_error "大模型API连接失败"
    fi
    
    # 检查QQ邮箱SMTP连接
    if nc -z smtp.qq.com 587 2>/dev/null; then
        print_success "QQ邮箱SMTP连接正常"
    else
        print_error "QQ邮箱SMTP连接失败"
    fi
}

# 显示系统信息
show_system_info() {
    print_info "系统信息:"
    echo "  操作系统: $(uname -s)"
    echo "  内核版本: $(uname -r)"
    echo "  主机名: $(hostname)"
    echo "  当前用户: $(whoami)"
    echo "  工作目录: $(pwd)"
    echo "  磁盘使用: $(df -h . | tail -1 | awk '{print $5}')"
}

# 主函数
main() {
    print_banner
    
    local exit_code=0
    
    # 检查各项
    check_python || exit_code=1
    echo ""
    
    check_dependencies || exit_code=1
    echo ""
    
    check_config || exit_code=1
    echo ""
    
    check_processes || exit_code=1
    echo ""
    
    check_system_service || exit_code=1
    echo ""
    
    check_logs
    echo ""
    
    check_network
    echo ""
    
    show_system_info
    echo ""
    
    # 显示总结
    echo "============================================================"
    if [ $exit_code -eq 0 ]; then
        print_success "系统状态检查完成 - 一切正常"
    else
        print_warning "系统状态检查完成 - 发现问题"
        echo ""
        echo "💡 建议操作:"
        echo "- 启动服务: ./start.sh"
        echo "- 重新配置: $PYTHON_CMD setup_email.py"
        echo "- 安装依赖: pip install -r requirements.txt"
    fi
    echo "============================================================"
    
    exit $exit_code
}

# 运行主函数
main "$@"
